<template>
  <div class="diet-tracking-form">
    <div class="food-intake-section">
      <FoodIntakeInput
        :foods="foods"
        v-model="formData.foods_intake"
      />
    </div>
    <div class="nutrition-preview" v-if="formData.foods_intake.length > 0">
      <h3>本次摄入营养预览</h3>
      <NutritionSummaryCard
        :nutrition="totalNutrition"
        :other-nutrients="totalOtherNutrients"
        :show-percentage="true"
        :show-detailed="true"
        :show-chart="false"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import type { Food, FoodIntake, NutritionSummary } from '@/types';
import { calculateTotalNutrition, mergeOtherNutrients } from '@/utils/nutrition';
import FoodIntakeInput from './FoodIntakeInput.vue';
import NutritionSummaryCard from './NutritionSummaryCard.vue';
import { useFoodsStore } from '@/stores/foods';

interface DietTrackingFormData {
  foods_intake: FoodIntake[];
}

interface Props {
  modelValue?: DietTrackingFormData;
}

interface Emits {
  (e: 'update:modelValue', data: DietTrackingFormData): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({ foods_intake: [] })
});
const emit = defineEmits<Emits>();

// Local state
const formData = ref<DietTrackingFormData>({ ...props.modelValue });

// Compute available foods
const foods = computed(() => {
  return foodsStore.foods.filter(
    (food) => food.id && food.name_zh
  ) as Food[];
});

// Compute total nutrition
const totalNutrition = computed<NutritionSummary>(() => {
  return calculateTotalNutrition(formData.value.foods_intake);
});

// Compute total other nutrients
const totalOtherNutrients = computed(() => {
  return mergeOtherNutrients(formData.value.foods_intake);
});

// Watch for formData changes and emit to parent
watch(formData, (newValue) => {
  emit('update:modelValue', { ...newValue });
}, { deep: true });

// Watch for props changes and sync to local state
watch(() => props.modelValue, (newValue) => {
  if (newValue && JSON.stringify(newValue) !== JSON.stringify(formData.value)) {
    formData.value = { ...newValue };
  }
}, { deep: true, immediate: true });

// Initialize foods data
const foodsStore = useFoodsStore();
onMounted(async () => {
  try {
    await foodsStore.fetchFoods();
    console.log('Foods loaded:', foodsStore.foods.length);
  } catch (error) {
    console.error('Failed to load foods:', error);
    // TODO: Display error notification
  }
});

// Reset form method
const resetForm = () => {
  formData.value = { foods_intake: [] };
};

// Expose resetForm to parent
defineExpose({ resetForm });
</script>

<style scoped>
.diet-tracking-form {
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}
.food-intake-section {
  margin: 0;
  padding: 12px;
  background: var(--ion-color-light);
  border-radius: 8px;
  width: 100%;
  box-sizing: border-box;
}
.nutrition-preview {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--ion-color-light);
  width: 100%;
}
.nutrition-preview h3 {
  margin: 0 0 12px 0;
  color: var(--ion-color-primary);
  font-size: 16px;
  font-weight: 600;
}
</style>